package jfdi;

import android.graphics.Canvas;
import android.util.JsonReader;

import util.Mlog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class NodeGroup extends Node {

    Layout mLayout;
    ArrayList<Node> mNodes;

    public NodeGroup(NodeHost host) {
        super(host);
        init();
    }

    @Override
    protected void init() {
        mLayout = new VerticalLayout(this);
    }

    public void attachNode(Node node) {
        if (mNodes == null) {
            mNodes = new ArrayList<Node>(5);
        }
        mNodes.add(node);
        if (mLayout.isLayedOut()) {
            // need to update the layout
            mLayout.layout(mLeft, mTop, mRight, mBottom);
        }
    }

    public List<Node> getNodes() {
        return mNodes;
    }
    
    @Override
    public int getMinWidth() {
        return mLayout.getMinWidth();
    }
    
    @Override
    public int getMinHeight() {
        return mLayout.getMinHeight();
    }

    @Override
    public void layout(int l, int t, int r, int b) {
        super.layout(l, t, r, b);
        mLayout.layout(l, t, r, b);
    }

    @Override
    public void draw(Canvas canvas) {
        final int n = mNodes.size();
        for (int i = 0; i < n; i++) {
            mNodes.get(i).draw(canvas);
        }
    }

    // serialization

    public void setAttribute(NodeHost host, String attr, JsonReader reader)
            throws IOException {
        Mlog.i("group", "group attribute: ", attr);
        if ("nodes".equals(attr)) {
            Mlog.i("json", "parsing nodes");
            reader.beginArray();
            while (reader.hasNext()) {
                Node child = JsonLoader.readNode(host, reader);
                attachNode(child);
            }
            reader.endArray();
        } else if ("layout".equals(attr)) {
            String lname = reader.nextString();
            setLayoutByName(lname);
        } else {
            setAttribute(host, attr, reader);
            mLayout.setAttribute(host, attr, reader);
        }
    }

    private void setLayoutByName(String name) {
        if ("horizontal".equals(name)) {
            mLayout = new HorizontalLayout(this);
        } else if ("vertical".equals(name)) {
            mLayout = new VerticalLayout(this);
        } else {
            Mlog.i("group", "unknown layout type: ", name);
        }
    }
}
